
package action.newelifile;

//import java.io.BufferedOutputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Locale;
import org.xmlpull.v1.XmlPullParser;
import action.adapter.LocalFileAdapter;
import action.pojo.LocalFilePojo;
import action.util.FavoriteConnectSQLite;
import action.util.LoadSetting;
import action.util.Tool;
import action.util.UsersDAO;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.media.ThumbnailUtils;
import android.graphics.Color;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore.Video.Thumbnails;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.Xml;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Toast;
import android.view.InflateException;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.LayoutInflater.Factory;
import android.view.View.OnClickListener;

public class LocalActivity extends Activity {
	public static String URL_LIST_PRODUCT = "http://14.63.212.204/eli-android-center/data/auto-update/listitem.xml";
	ProgressDialog mProgressDialog;
	public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
	String link = "";
	String newversion="";
	String oldversion="";

	Button expandButton,addressButton,switchButton,backButton,changeViewButton,uploadButton,sortButton,multiButton,mBackButton,
	mCopyButton,mCutButton,mDeleteButton,mCancelButton;
	ImageView imageView1,imageView2,imageMobile,imageSdcard;
	GridView gridView;
	ListView listView,listDetailView;
	TextView txtViewEmpty,tvwaitingup;

	ArrayList<LocalFilePojo> local_list;
	LocalFileAdapter adapter;
	ArrayList<LocalFilePojo> multiSelect = new ArrayList<LocalFilePojo>();
	boolean multi = false; // kiem tra xem dang o trang thai multi
	int multiAction = 0; // kiem tra xem da chon copy cu de luu trang thai va co; 1 la cut
	int sortlist = 0;
	Dialog dialog;

	LinearLayout expandLayout;
	String[] operator;
	int flagCopyCut = 0; // 1 copy, 2 cut

	File copy, cut;
	String srcpath="";
	LocalFilePojo objectCut= new LocalFilePojo();

//	private final Handler uiHandlerup=new Handler();
//	private boolean isUpdateRequiredup=false;

	public FavoriteConnectSQLite favoriteConnectSQLite;

	LayoutInflater inflaterwaiting;
	View textEntryViewwaiting;
	AlertDialog.Builder builderwaiting;
	AlertDialog alertwaiting;
	AsyncTask<String, String, Void> asyn;
	
	public static int screenheight,screenwidth;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		try{
			LoadSetting.load(this);
			initLocale();
			setContentView(R.layout.main);

			favoriteConnectSQLite = new FavoriteConnectSQLite(this);
			favoriteConnectSQLite.open();

			initAttribute();
			initdata();
			LoadSetting.loadTheme(this);
			Tool.position = 1;
			checkUpdate();
			processButton();
			
			DisplayMetrics displaymetrics = new DisplayMetrics();
			getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
			screenheight = displaymetrics.heightPixels;
			screenwidth = displaymetrics.widthPixels;
			
			super.onCreate(savedInstanceState);
		}catch(Exception e){
			e.printStackTrace();
			Intent i = getBaseContext().getPackageManager().getLaunchIntentForPackage( getBaseContext().getPackageName() );
			i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(i);
		}

	}

	public void initAttribute(){
		expandButton = (Button)findViewById(R.id.expandButton);
		addressButton = (Button)findViewById(R.id.addressButton);
		switchButton = (Button)findViewById(R.id.switchButton);
		backButton = (Button)findViewById(R.id.backButton);
		changeViewButton = (Button)findViewById(R.id.changeViewButton);
		uploadButton = (Button)findViewById(R.id.uploadButton);
		sortButton = (Button)findViewById(R.id.sortButton);
		multiButton = (Button)findViewById(R.id.multiButton);
		mBackButton = (Button)findViewById(R.id.mBackButton);
		mCopyButton = (Button)findViewById(R.id.mCopyButton);
		mCutButton = (Button)findViewById(R.id.mCutButton);
		mDeleteButton = (Button)findViewById(R.id.mDeleteButton);
		mCancelButton = (Button)findViewById(R.id.mCancelButton);

		imageView1 = (ImageView)findViewById(R.id.imageView1);
		imageView2 = (ImageView)findViewById(R.id.imageView2);
		imageMobile = (ImageView)findViewById(R.id.imageMobile);
		imageSdcard = (ImageView)findViewById(R.id.imageSdcard);

		gridView = (GridView)findViewById(R.id.gridView);

		listView = (ListView)findViewById(R.id.listView);
		listDetailView = (ListView)findViewById(R.id.listDetailView);

		txtViewEmpty = (TextView)findViewById(R.id.txtViewEmpty);

		expandLayout = (LinearLayout)findViewById(R.id.expandLayout);


		inflaterwaiting = (LayoutInflater) getApplicationContext().getSystemService(LAYOUT_INFLATER_SERVICE);          
		textEntryViewwaiting = inflaterwaiting.inflate(R.layout.waiting, null);
		tvwaitingup=(TextView)textEntryViewwaiting.findViewById(R.id.TextView01);					
		tvwaitingup.setText(R.string.waiting+"...");

		builderwaiting = new AlertDialog.Builder(LocalActivity.this);
		builderwaiting.setView(textEntryViewwaiting);
		builderwaiting.setCancelable(false);
		alertwaiting = builderwaiting.create();

		Tool.list_favorite = getFavorite();
		if (Tool.list_favorite == null)
			Tool.list_favorite = new ArrayList<LocalFilePojo>();

	}

	public void initLocale(){
		String languageToLoad = Tool.locale(LoadSetting.setting.getLanguage());  
		Locale locale = new Locale(languageToLoad);   
		Locale.setDefault(locale);  
		Configuration config = new Configuration();  
		config.locale = locale;  
		getBaseContext().getResources().updateConfiguration(config,   
				getBaseContext().getResources().getDisplayMetrics());  


	}

	private void initdata(){
		Bundle param = getIntent().getExtras();
		if(param!=null){
			if(param.get("paths").equals("addActi")){
				refresh();
			}
		}else{
			Tool.local_path= new ArrayList<String>();
			Tool.strlocal_path=Environment.getExternalStorageDirectory().toString();
			System.out.println("root: "+Tool.strlocal_path);
			String[] tem= Tool.strlocal_path.split(File.separator);
			if(tem!=null && tem.length>0){
				for(String s: tem){
					if(!s.equals(null) && !s.equals("")){
						Tool.local_path.add(s);
					}
				}
				refresh();
			}
		}
	}

	@Override
	protected void onResume() {
		try{
			super.onResume();
			if(getIntent() != null){
				Intent intent = getIntent();
				if(intent.getExtras() != null){
					boolean isSearch = intent.getExtras().getBoolean("isSearch");
					String src = intent.getStringExtra("src");
					if(isSearch){
						String[] temp = src.toString().split(File.separator);
						Tool.local_path = new ArrayList<String>();
						for(String value : temp){
							Tool.local_path.add(value);
						}
						for (int i = 0; i < Tool.local_path.size(); i++) {
							System.out.println(Tool.local_path.get(i));
						}
						LoadSetting.load(this);
					}
				}
			}
			refresh();
		}catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void setValueOperator() {
		operator = new String[] { LocalActivity.this.getString(R.string.select_all) };
	}

	public void refresh() {
		local_list = getListFile(Tool.getLocalPath(Tool.local_path));
		switch (LoadSetting.setting.getDisplay()) {
		case 0:
			// gridview
			initalGridView();
			break;
		case 1:
			// list_view;
			initalListView();
			break;
		case 2:
			// detail_view;
			initalDetailView();
			break;
		default:
			break;
		}
		addressButton.setText(Tool.getLocalPath(Tool.local_path));
	}

	private void initalListView() {
		gridView.setVisibility(GridView.GONE);
		listView.setVisibility(ListView.VISIBLE);
		listDetailView.setVisibility(ListView.GONE);
		if(local_list!=null && local_list.size()>0){
			adapter = new LocalFileAdapter(LocalActivity.this, R.layout.list_view, local_list);
			listView.setAdapter(adapter);
			listView.setOnItemClickListener(onListFileClick());
			listView.setOnItemLongClickListener(itemLongClick());
		}else{
			listView.setVisibility(ListView.GONE);
			txtViewEmpty.setVisibility(TextView.VISIBLE);
			txtViewEmpty.setText("Folder empty");
		}
	}

	private void initalGridView() {
		gridView.setVisibility(GridView.VISIBLE);
		listView.setVisibility(ListView.GONE);
		listDetailView.setVisibility(ListView.GONE);
		if(local_list!=null && local_list.size()>0){
			adapter = new LocalFileAdapter(LocalActivity.this, R.layout.grid_detail,local_list);
			gridView.setAdapter(adapter);
			gridView.setOnItemClickListener(onListFileClick());
			gridView.setOnItemLongClickListener(itemLongClick());
		}else{
			gridView.setVisibility(ListView.GONE);
			txtViewEmpty.setVisibility(TextView.VISIBLE);
			txtViewEmpty.setText("Folder empty");
		}
	}

	private void initalDetailView() {
		gridView.setVisibility(GridView.GONE);
		listView.setVisibility(ListView.GONE);
		listDetailView.setVisibility(ListView.VISIBLE);
		if(local_list!=null && local_list.size()>0){
			adapter = new LocalFileAdapter(LocalActivity.this, R.layout.list_detail,local_list);
			listDetailView.setAdapter(adapter);
			listDetailView.setOnItemClickListener(onListFileClick());
			listDetailView.setOnItemLongClickListener(itemLongClick());
		}else{
			listDetailView.setVisibility(ListView.GONE);
			txtViewEmpty.setVisibility(TextView.VISIBLE);
			txtViewEmpty.setText("Folder empty");
		}
	}

	private OnItemClickListener onListFileClick() {
		OnItemClickListener action = new OnItemClickListener() {

			public void onItemClick(AdapterView<?> array, View arg1,
					int postion, long arg3) {
				LocalFilePojo item = (LocalFilePojo) array.getItemAtPosition(postion);
				if (multi) {
					if(multiSelect!=null){
						local_list.get(postion).setChecked(!local_list.get(postion).isChecked());
						if(multiSelect.contains(item)){
							multiSelect.remove(item);
							tongmulti-=item.getTotalsize();
						}else{
							multiSelect.add(item);
							tongmulti+=item.getTotalsize();
						}
					}
					adapter.notifyDataSetChanged();
					System.out.println("multi size: "+multiSelect.size()+" -- "+tongmulti);
				} else {
					if (item.getFileItem().isDirectory()) {
						Tool.local_path.add(item.getFileItem().getName());
						refresh();
					} else {
						startActivity(item.getAction());
					}
					int a = checkExistFile(item, Tool.list_history);
					if (a != -1)
						Tool.list_history.remove(a);
					Tool.list_history.add(item);
				}
			}
		};
		return action;
	}

	public OnItemLongClickListener itemLongClick() {
		OnItemLongClickListener longClickListener = new OnItemLongClickListener() {

			public boolean onItemLongClick(AdapterView<?> parent, View view,
					int position, long id) {
				LocalFilePojo object = (LocalFilePojo) parent.getItemAtPosition(position);
				System.out.println("object: "+object.getFileItem().getPath()+" -- sopah: "+object.getFileItem().getAbsolutePath());
				openLongOptionDialog(object);
				return true;
			}
		};
		return longClickListener;
	}

	public void openLongOptionDialog(final LocalFilePojo item) {
		try {
			String[] list = LocalActivity.this.getResources().getStringArray(R.array.option_arr);
			dialog = new Dialog(LocalActivity.this);
			dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
			dialog.setContentView(R.layout.popup_switch);
			((TextView)dialog.findViewById(R.id.tvHeader)).setText(R.string.option);
			ListView listview = (ListView) dialog.findViewById(R.id.lvSwith);
			listview.setAdapter(new ArrayAdapter<String>(LocalActivity.this,R.layout.list_option,list));
			listview.setOnItemClickListener(longMenuClick(item));
			((Button) dialog.findViewById(R.id.cancel)).setOnClickListener(new OnClickListener() {					

				public void onClick(View v) {
					dialog.dismiss();
				}
			});
			dialog.setCanceledOnTouchOutside(true);
			dialog.show();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private OnItemClickListener longMenuClick(final LocalFilePojo item){
		OnItemClickListener action = new OnItemClickListener() {
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				switch (arg2) {
				case 0:
					if(multi){
						setValuePasteOperator();
						String str = LocalActivity.this.getString(R.string.havejustchosen) + " : \n";
						for (int i = 0; i < multiSelect.size(); i++) {
							str += " - " + multiSelect.get(i).getFileItem().getPath() + "\n";
						}
						Toast.makeText(LocalActivity.this, str, Toast.LENGTH_SHORT).show();
						multiAction = 1; // 1 la copy
						flagCopyCut = 0;
						multi = false;
						srcpath=Tool.getLocalPath(Tool.local_path);
						refresh();
						((LinearLayout) LocalActivity.this.findViewById(R.id.multiLayout))
						.setVisibility(LinearLayout.GONE);
						((LinearLayout) LocalActivity.this.findViewById(R.id.normalLayout))
						.setVisibility(LinearLayout.VISIBLE);
						Toast.makeText(LocalActivity.this, R.string.multioff, Toast.LENGTH_SHORT)
						.show();
					}else{
						flagCopyCut = 1;
						multiAction = 0;
						setValuePasteOperator();
						multi = false;
						copy = item.getFileItem();
						srcpath=Tool.getLocalPath(Tool.local_path);
						refresh();
						Toast.makeText(LocalActivity.this, getString(R.string.havejustchosen) + " " + copy.getName(),
								Toast.LENGTH_SHORT).show();
						((LinearLayout) LocalActivity.this.findViewById(R.id.multiLayout))
						.setVisibility(LinearLayout.GONE);
						((LinearLayout) LocalActivity.this.findViewById(R.id.normalLayout))
						.setVisibility(LinearLayout.VISIBLE);
						Toast.makeText(LocalActivity.this, R.string.multioff, Toast.LENGTH_SHORT)
						.show();
					}
					break;
				case 1:
					//					flagCopyCut = 2;
					//					multiAction = 0;
					//					moveOne(item.getPath());
					//					((Button) activity.findViewById(R.id.searchButton))
					//					.setCompoundDrawablesWithIntrinsicBounds(null,activity.getResources().getDrawable(R.drawable.paste),null,null);
					//					((Button) activity.findViewById(R.id.searchButton)).setText(R.string.paste);
					//					((Button) activity.findViewById(R.id.searchButton)).setOnClickListener(pasteAction());

					if(multi){
						setValuePasteOperator();
						String str = LocalActivity.this.getString(R.string.havejustchosen) + " : \n";
						for (int i = 0; i < multiSelect.size(); i++) {
							str += " - " + multiSelect.get(i).getFileItem().getPath() + "\n";
						}
						Toast.makeText(LocalActivity.this, str, Toast.LENGTH_SHORT).show();
						multiAction = 2; // 1 la copy
						flagCopyCut = 0;
						multi = false;
						srcpath=Tool.getLocalPath(Tool.local_path);
						refresh();
						((LinearLayout) LocalActivity.this.findViewById(R.id.multiLayout))
						.setVisibility(LinearLayout.GONE);
						((LinearLayout) LocalActivity.this.findViewById(R.id.normalLayout))
						.setVisibility(LinearLayout.VISIBLE);
						Toast.makeText(LocalActivity.this, R.string.multioff, Toast.LENGTH_SHORT)
						.show();
					}else{
						flagCopyCut = 2;
						multiAction = 0;
						setValuePasteOperator();
						multi = false;
						objectCut=item;
						tongmulti = item.getTotalsize();
						srcpath=Tool.getLocalPath(Tool.local_path);
						refresh();
						Toast.makeText(LocalActivity.this, getString(R.string.havejustchosen) + " " + objectCut.getFileItem().getName(),
								Toast.LENGTH_SHORT).show();
						((LinearLayout) LocalActivity.this.findViewById(R.id.multiLayout))
						.setVisibility(LinearLayout.GONE);
						((LinearLayout) LocalActivity.this.findViewById(R.id.normalLayout))
						.setVisibility(LinearLayout.VISIBLE);
						Toast.makeText(LocalActivity.this, R.string.multioff, Toast.LENGTH_SHORT)
						.show();
					}
					break;
				case 2:
					remove(item);
					break;
				case 3:
					rename(item.getFileItem().getPath());
					break;
				case 4:
					details(item);
					break;
				case 5:
					favorite(item);
					break;
				default:
					break;
				}
				if(dialog.isShowing())dialog.dismiss();
			}
		};
		return action;
	}
	
	public void favorite(LocalFilePojo item){
		if (multi) {
			if(multiSelect!=null && multiSelect.size()>0){
				for (int i = 0; i < multiSelect.size(); i++) {
					saveFavorite(multiSelect.get(i));
					item.setFavorite(true);
					
					adapter.notifyDataSetChanged();
				}
				
				multi=false;
				cut = copy = null;
				multiSelect.clear();
				((LinearLayout) LocalActivity.this.findViewById(R.id.multiLayout))
				.setVisibility(LinearLayout.GONE);
				((LinearLayout) LocalActivity.this.findViewById(R.id.normalLayout))
				.setVisibility(LinearLayout.VISIBLE);
				Toast.makeText(LocalActivity.this, R.string.multioff, Toast.LENGTH_SHORT)
				.show();
			}
			adapter.notifyDataSetChanged();
		}else{
			if(!item.isFavorite()){
				saveFavorite(item);
				item.setFavorite(true);
			}else{
				saveFavorite(item);
				item.setFavorite(false);
			}
			adapter.notifyDataSetChanged();
		}
		
		
	}

	private ArrayList<LocalFilePojo> getListFile(String path) {
		ArrayList<LocalFilePojo> all = new ArrayList<LocalFilePojo>();
		ArrayList<LocalFilePojo> files = new ArrayList<LocalFilePojo>();
		ArrayList<LocalFilePojo> folders = new ArrayList<LocalFilePojo>();
		File dir = new File(path);
		Intent action = null;
		Bitmap bitmap = null;
		Drawable icon = null;
		LocalFilePojo item;
		BitmapFactory.Options options=new BitmapFactory.Options();
		options.inSampleSize = 8;
		try {
			for (File f : dir.listFiles()) {
				if (f.canRead()) {
					if (f.isFile()) {
						action = new Intent(Intent.ACTION_VIEW);
						if (Tool.checkExtendFile(f.getName(), ".txt")
								|| Tool.checkExtendFile(f.getName(), ".csv")) {
							icon = LocalActivity.this.getResources().getDrawable(
									R.drawable.text_file);
							action.setDataAndType(Uri.fromFile(f), "text/*");
						} else if (Tool.checkExtendFile(f.getName(), ".xml")) {
							icon = LocalActivity.this.getResources().getDrawable(
									R.drawable.xml_file);
							action.setDataAndType(Uri.fromFile(f), "text/*");
						} else if (Tool.checkExtendFile(f.getName(), ".flv")
								|| Tool.checkExtendFile(f.getName(), ".3gp")
								|| Tool.checkExtendFile(f.getName(), ".avi")) {
							bitmap = ThumbnailUtils.createVideoThumbnail(
									f.getAbsolutePath(), Thumbnails.MICRO_KIND);
							icon = new BitmapDrawable(bitmap);
							action.setDataAndType(Uri.fromFile(f), "video/*");
						} else if (Tool.checkExtendFile(f.getName(), ".mp3")) {
							icon = LocalActivity.this.getResources().getDrawable(
									R.drawable.mp3_file);
							action.setDataAndType(Uri.fromFile(f), "audio/*");
						} else if (Tool.checkExtendFile(f.getName(), ".doc")
								|| Tool.checkExtendFile(f.getName(), ".docx")) {
							icon = LocalActivity.this.getResources().getDrawable(
									R.drawable.word_file);
							action.setDataAndType(Uri.fromFile(f), "text/*");
						} else if (Tool.checkExtendFile(f.getName(), ".ppt")
								|| Tool.checkExtendFile(f.getName(), ".pptx")) {
							icon = LocalActivity.this.getResources().getDrawable(
									R.drawable.pptx_file);
							action.setDataAndType(Uri.fromFile(f), "text/*");
						} else if (Tool.checkExtendFile(f.getName(), ".xls")
								|| Tool.checkExtendFile(f.getName(), ".xlsx")) {
							icon = LocalActivity.this.getResources().getDrawable(
									R.drawable.xlsx_file);
							action.setDataAndType(Uri.fromFile(f), "text/*");
						} else if (Tool.checkExtendFile(f.getName(), ".zip")
								|| Tool.checkExtendFile(f.getName(), ".rar")) {
							icon = LocalActivity.this.getResources().getDrawable(
									R.drawable.rar_file);
							action.setDataAndType(Uri.fromFile(f), "video/*");
						} else if (Tool.checkExtendFile(f.getName(), ".jpg")
								|| Tool.checkExtendFile(f.getName(), ".jpeg")
								|| Tool.checkExtendFile(f.getName(), ".png")
								|| Tool.checkExtendFile(f.getName(), ".bmp")
								|| Tool.checkExtendFile(f.getName(), ".gif")) {
							bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),options);
							icon = new BitmapDrawable(bitmap);
							action.setDataAndType(Uri.fromFile(f), "image/*");
						} else if (Tool.checkExtendFile(f.getName(), ".apk")) {
							icon = LocalActivity.this.getResources().getDrawable(
									R.drawable.apk_file);
							action.setDataAndType(Uri.fromFile(f),
							"application/vnd.android.package-archive");
						} else if (Tool.checkExtendFile(f.getName(), ".exe")) {
							icon = LocalActivity.this.getResources().getDrawable(
									R.drawable.exe_file);
						} else {
							icon = LocalActivity.this.getResources().getDrawable(
									R.drawable.unknown_file);
						}
						item = new LocalFilePojo(f,icon,action);
						files.add(item);
					} else if (f.isDirectory()) {
						icon = LoadSetting.loadFolder(LocalActivity.this);
						item = new LocalFilePojo(f, icon);
						folders.add(item);
					}
				}
			}

			Tool.sortLocal(files, 0);
			Tool.sortLocal(folders, 0);

			all.addAll(folders);
			all.addAll(files);

			if(Tool.list_favorite.size() > 0 && all.size() > 0){
				for(int i = 0;i<Tool.list_favorite.size();i++){
					for(int y=0;y<all.size();y++){
						if(Tool.list_favorite.get(i).getPath().equals(File.separator+all.get(y).getFileItem().getPath())){
							all.get(y).setFavorite(true);
						}
					}
				}
			}
		} catch (NullPointerException e) {
			e.printStackTrace();
			return null;
		}
		return all;
	}

	// process button
	public void processButton(){
		expandButton.setOnClickListener(processButtonExpand());
		backButton.setOnClickListener(processButtonBack());
		addressButton.setOnClickListener(processButtonAddress());
		switchButton.setOnClickListener(processSwitchButton());
		changeViewButton.setOnClickListener(processButtonChangeview());
		sortButton.setOnClickListener(processButtonSort());
		multiButton.setOnClickListener(processButtonMulti());
		mCancelButton.setOnClickListener(processButtonCancel_multioff());
		uploadButton.setOnClickListener(processButtonUpload());
		mDeleteButton.setOnClickListener(processButtonDelete());
		mCopyButton.setOnClickListener(processButtonCopy());
		mCutButton.setOnClickListener(processButtonCut());
	}

	private OnClickListener processButtonCut(){
		OnClickListener onclick = new OnClickListener() {
			@Override
			public void onClick(View v) {
				try {
					if (multiSelect.size() == 0) {
						AlertDialog.Builder builder = new AlertDialog.Builder(LocalActivity.this);
						builder.setTitle(LocalActivity.this.getString(R.string.warning));
						builder.setMessage(LocalActivity.this.getString(R.string.chooseafilecopy));
						builder.show();
						return;
					}
					setValuePasteOperator();
					String str = LocalActivity.this.getString(R.string.havejustchosen) + " : \n";
					for (int i = 0; i < multiSelect.size(); i++) {
						str += " - " + multiSelect.get(i).getFileItem().getPath() + "\n";
					}
					Toast.makeText(LocalActivity.this, str, Toast.LENGTH_SHORT).show();
					multiAction = 2; // 1 la copy
					flagCopyCut = 0;
					multi = false;
					srcpath=Tool.getLocalPath(Tool.local_path);
					refresh();
					((LinearLayout) LocalActivity.this.findViewById(R.id.multiLayout))
					.setVisibility(LinearLayout.GONE);
					((LinearLayout) LocalActivity.this.findViewById(R.id.normalLayout))
					.setVisibility(LinearLayout.VISIBLE);
					Toast.makeText(LocalActivity.this, R.string.multioff, Toast.LENGTH_SHORT)
					.show();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		};
		return onclick;
	}

	private OnClickListener processButtonCopy(){
		OnClickListener onclick = new OnClickListener() {

			@Override
			public void onClick(View v) {
				try {
					if (multiSelect.size() == 0) {
						AlertDialog.Builder builder = new AlertDialog.Builder(LocalActivity.this);
						builder.setTitle(LocalActivity.this.getString(R.string.warning));
						builder.setMessage(LocalActivity.this.getString(R.string.chooseafilecopy));
						builder.show();
						return;
					}
					setValuePasteOperator();
					String str = LocalActivity.this.getString(R.string.havejustchosen) + " : \n";
					for (int i = 0; i < multiSelect.size(); i++) {
						str += " - " + multiSelect.get(i).getFileItem().getPath() + "\n";
					}
					Toast.makeText(LocalActivity.this, str, Toast.LENGTH_SHORT).show();
					multiAction = 1; // 1 la copy
					flagCopyCut = 0;
					multi = false;
					srcpath=Tool.getLocalPath(Tool.local_path);
					refresh();
					((LinearLayout) LocalActivity.this.findViewById(R.id.multiLayout))
					.setVisibility(LinearLayout.GONE);
					((LinearLayout) LocalActivity.this.findViewById(R.id.normalLayout))
					.setVisibility(LinearLayout.VISIBLE);
					Toast.makeText(LocalActivity.this, R.string.multioff, Toast.LENGTH_SHORT)
					.show();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		};
		return onclick;
	}

	public OnClickListener processButtonUpload(){
		OnClickListener onclick = new OnClickListener() {

			@Override
			public void onClick(View v) {
				if(multiSelect!=null && multiSelect.size()>0){
					Intent intent = new Intent(LocalActivity.this,MainFTPActivity.class);
					startActivity(intent);
					finish();
				}else{
					Toast.makeText(LocalActivity.this, LocalActivity.this.getString(R.string.please_choose_item_to_upload), Toast.LENGTH_SHORT).show();
				}

			}
		};
		return onclick;
	}

	public OnClickListener processButtonDelete(){
		OnClickListener onclick = new OnClickListener() {
			@Override
			public void onClick(View v) {
				try {
					AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(LocalActivity.this);
					dialogBuilder.setTitle(getString(R.string.delete));
					dialogBuilder.setMessage(getString(R.string.areyousure));
					dialogBuilder.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {

							if (multi) {
								if(multiSelect!=null && multiSelect.size()>0){
									for (int i = 0; i < multiSelect.size(); i++) {
										deleteRecursive(multiSelect.get(i).getFileItem());
									}
									multi=false;
									refresh();
									cut = copy = null;
									multiSelect.clear();
									((LinearLayout) LocalActivity.this.findViewById(R.id.multiLayout))
									.setVisibility(LinearLayout.GONE);
									((LinearLayout) LocalActivity.this.findViewById(R.id.normalLayout))
									.setVisibility(LinearLayout.VISIBLE);
									Toast.makeText(LocalActivity.this, R.string.multioff, Toast.LENGTH_SHORT)
									.show();
								}
							}
						}
					});
					dialogBuilder.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {

						}
					});

					AlertDialog al = dialogBuilder.create();
					al.show();
				} catch (Exception e) {
					e.printStackTrace(System.out);
				}
			}
		};
		return onclick;
	}

	public OnClickListener processButtonCancel_multioff(){
		OnClickListener onclick = new OnClickListener() {

			@Override
			public void onClick(View v) {
				multi = false;
				multiAction = 0;
				flagCopyCut = 0;
				multiSelect.clear();
				((LinearLayout) LocalActivity.this.findViewById(R.id.multiLayout))
				.setVisibility(LinearLayout.GONE);
				((LinearLayout) LocalActivity.this.findViewById(R.id.normalLayout))
				.setVisibility(LinearLayout.VISIBLE);
				Toast.makeText(LocalActivity.this, R.string.multioff, Toast.LENGTH_SHORT)
				.show();
				for(LocalFilePojo t:local_list){
					if(t.isChecked())t.setChecked(false);
				}
				adapter.notifyDataSetChanged();
			}
		};
		return onclick;
	}

	public OnClickListener processButtonMulti(){
		OnClickListener onclick = new OnClickListener() {

			@Override
			public void onClick(View v) {
				multi = true;
				multiAction = 0;
				flagCopyCut = 0;
				multiSelect.clear();
				tongmulti=0;
				((LinearLayout) LocalActivity.this.findViewById(R.id.multiLayout))
				.setVisibility(LinearLayout.VISIBLE);
				((LinearLayout) LocalActivity.this.findViewById(R.id.normalLayout))
				.setVisibility(LinearLayout.GONE);
				Toast.makeText(LocalActivity.this, R.string.multion, Toast.LENGTH_SHORT)
				.show();
			}
		};
		return onclick;
	}

	public OnClickListener processButtonSort(){
		OnClickListener onclick = new OnClickListener() {

			@Override
			public void onClick(View v) {
				String[] list = new String[] {LocalActivity.this.getResources().getString(R.string.name), LocalActivity.this.getResources().getString(R.string.size), LocalActivity.this.getResources().getString(R.string.lastmodified) };
				dialog = new Dialog(LocalActivity.this);
				dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
				dialog.setContentView(R.layout.popup_switch);
				((TextView)dialog.findViewById(R.id.tvHeader)).setText(R.string.sort);

				ListView listview = (ListView) dialog.findViewById(R.id.lvSwith);
				listview.setAdapter(new ArrayAdapter<String>(LocalActivity.this,
						android.R.layout.select_dialog_singlechoice, list));
				listview.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
				listview.setItemChecked(sortlist, true);
				listview.setOnItemClickListener(sortClick());

				((Button)dialog.findViewById(R.id.cancel)).setOnClickListener(new OnClickListener() {					

					public void onClick(View v) {
						dialog.dismiss();
					}
				});
				dialog.setCanceledOnTouchOutside(true);
				dialog.show();
			}
		};
		return onclick;
	}

	private OnItemClickListener sortClick() {
		OnItemClickListener action = new OnItemClickListener() {			
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				switch (arg2) {
				case 0:
					local_list = Tool.sortLocal(local_list, 0);
					sortlist = 0;
					break;
				case 1:
					local_list = Tool.sortLocal(local_list, 1);
					sortlist = 1;
					break;
				case 2:
					local_list = Tool.sortLocal(local_list, 2);
					sortlist = 2;
					break;
				}	
				refreshAdapter();
				dialog.dismiss();
			}	
		};

		return action;

	}

	public void refreshAdapter() {
		switch (LoadSetting.setting.getDisplay()) {
		case 0:
			// gridview
			initalGridView();
			break;
		case 1:
			// list_view;
			initalListView();
			break;
		case 2:
			// detail_view;
			initalDetailView();
			break;
		default:
			break;
		}
	}

	public OnClickListener processButtonChangeview(){
		OnClickListener onclick = new OnClickListener() {
			@Override
			public void onClick(View v) {
				try {
					String[] list = new String[] {getResources().getString(R.string.girdview),getResources().getString(R.string.listview), 
							getResources().getString(R.string.detailview) };
					dialog = new Dialog(LocalActivity.this);
					dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
					dialog.setContentView(R.layout.popup_switch);
					((TextView)dialog.findViewById(R.id.tvHeader)).setText(R.string.changeView);
					ListView listview = (ListView) dialog.findViewById(R.id.lvSwith);
					listview.setAdapter(new ArrayAdapter<String>(LocalActivity.this,R.layout.list_option,list));
					listview.setOnItemClickListener(changeViewClick());
					((Button) dialog.findViewById(R.id.cancel)).setOnClickListener(new OnClickListener() {					

						public void onClick(View v) {
							dialog.dismiss();
						}
					});
					dialog.setCanceledOnTouchOutside(true);
					dialog.show();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		};
		return onclick;
	}

	private OnItemClickListener changeViewClick(){
		OnItemClickListener action =new  OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				if (arg2==0) {
					LoadSetting.setting.setDisplay(0);
				}
				if (arg2==1) {
					LoadSetting.setting.setDisplay(1);
				}
				if (arg2==2) {
					LoadSetting.setting.setDisplay(2);
				}
				UsersDAO user  = new UsersDAO(LocalActivity.this);
				user.saveData(LoadSetting.setting.getBackground(), LoadSetting.setting.getDisplay(), LoadSetting.setting.getLanguage(), LoadSetting.setting.getIcon());
				refresh();
				dialog.dismiss();
			}
		};
		return action;
	}

	// process button expand
	public OnClickListener processButtonExpand(){
		OnClickListener onclick = new  View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if(expandLayout.getVisibility()==LinearLayout.GONE){
					expandLayout.setVisibility(LinearLayout.VISIBLE);
					expandButton.setCompoundDrawablesWithIntrinsicBounds(null, getResources().getDrawable(R.drawable.subtract), null,null);
				}else{
					expandLayout.setVisibility(LinearLayout.GONE);
					expandButton.setCompoundDrawablesWithIntrinsicBounds(null, getResources().getDrawable(R.drawable.plus), null,null);
				}
			}
		};
		return onclick;
	}

	public void back() {
		if (Tool.local_path.size() > 2) {
			Tool.local_path.remove(Tool.local_path.size() - 1);
			if (multi) {
				multi = false;
				multiSelect.clear();
			} else {
				multi = false;
			}
			refresh();
		}else{
			if((File.separator+Tool.getLocalPath(Tool.local_path)).equals(Tool.strlocal_path)){
				runExit();
			}else{
				if(Tool.local_path.size() > 1){
					Tool.local_path.remove(Tool.local_path.size() - 1);
					if (multi) {
						multi = false;
						multiSelect.clear();
					} else {
						multi = false;
					}
					refresh();
				}else{
					runExit();
				}
			}

		}

	}

	// process button back
	public OnClickListener processButtonBack(){
		OnClickListener action = new OnClickListener() {

			@Override
			public void onClick(View v) {
				back();
			}
		};
		return action;
	}

	// process button address
	public OnClickListener processButtonAddress(){
		OnClickListener onclick = new OnClickListener() {

			@Override
			public void onClick(View v) {
				Tool.list_favorite = getFavorite();
				Intent intent = new Intent(LocalActivity.this, AddressActivity.class);
				startActivity(intent);
			}
		};
		return onclick;
	}

	private ArrayList<LocalFilePojo> getFavorite() {
		Tool.list_favorite = (ArrayList<LocalFilePojo>) favoriteConnectSQLite.getAllConnect();

		return Tool.list_favorite;
	}

	private OnClickListener processSwitchButton() {
		OnClickListener action = new OnClickListener() {

			public void onClick(View v) {
				String[] list = new String[] { "Local", "LAN", "FTP" };
				dialog = new Dialog(LocalActivity.this);
				dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
				dialog.setContentView(R.layout.popup_switch);
				((TextView)dialog.findViewById(R.id.tvHeader)).setText(R.string.switch_to);
				ListView listview = (ListView) dialog.findViewById(R.id.lvSwith);
				listview.setAdapter(new ArrayAdapter<String>(LocalActivity.this,android.R.layout.select_dialog_singlechoice, list));
				listview.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
				listview.setItemChecked(0, true);
				listview.setOnItemClickListener(switchToClick());
				((Button) dialog.findViewById(R.id.cancel)).setOnClickListener(new OnClickListener() {					

					public void onClick(View v) {
						dialog.dismiss();
					}
				});
				dialog.setCanceledOnTouchOutside(true);
				dialog.show();
			}
		};
		return action;
	}

	private OnItemClickListener switchToClick() {
		OnItemClickListener action = new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				//				Intent intent = null;
				System.out.println("arg == " + arg2);
				if (arg2==0) {
					dialog.dismiss();
					return;
				}if (arg2==1){
					Intent intent = new Intent(LocalActivity.this, LanActivity.class);
					startActivity(intent);
					finish();
				}if (arg2==2){
					Intent intent = new Intent(LocalActivity.this,FtpActivity.class);
					startActivity(intent);
					finish();
				}
				dialog.dismiss();

			}
		};
		return action;
	}

	// check auto update
	private void checkUpdate(){
		if(getCheckProduct()==false){
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setTitle(getString(R.string.update_new_version));
			builder.setMessage(getString(R.string.ELiFile_find_new_version)+newversion+"\n"
					+ getString(R.string.would_you_like_to_update));
			builder.setPositiveButton(getString(R.string.ok),
					new AlertDialog.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog,int which) {
					downloading();
				}
			});
			builder.setNegativeButton(getString(R.string.cancel),
					new AlertDialog.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog,
						int which) {
				}
			});
			builder.show();
		}
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DIALOG_DOWNLOAD_PROGRESS:
			mProgressDialog = new ProgressDialog(this);
			mProgressDialog.setMessage(getString(R.string.downloading)+" ...");
			mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			mProgressDialog.setCancelable(false);
			mProgressDialog.show();
			return mProgressDialog;
		default:
			return null;
		}
	}

	public void downloading() {
		new AsyncTask<String, String, String>() {

			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				showDialog(DIALOG_DOWNLOAD_PROGRESS);
			}

			protected void onProgressUpdate(String... progress) {
				mProgressDialog.setProgress(Integer.parseInt(progress[0]));
			}

			@Override
			protected void onPostExecute(String unused) {
				dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
				finish();
			}

			@Override
			protected String doInBackground(String... arg0) {
				try {
					URL url = new URL(link);
					HttpURLConnection c = (HttpURLConnection) url
					.openConnection();
					c.setRequestMethod("GET");
					c.setDoOutput(true);
					c.connect();

					File file = new File(
							Environment.getExternalStorageDirectory()
							+ "/elicenter/");
					if (!file.exists()) {
						file.mkdir();
					}

					file = new File(Environment.getExternalStorageDirectory()
							+ "/elicenter/" + "EliFile.apk");
					if (!file.exists()) {
						file.createNewFile();
					}

					File outputFile = new File(
							Environment.getExternalStorageDirectory()
							+ "/elicenter/" + "EliFile.apk");
					FileOutputStream fos = new FileOutputStream(outputFile);

					InputStream is = c.getInputStream();

					byte[] buffer = new byte[1024];

					long total = 0;
					int count;
					int lenghtOfFile = c.getContentLength();
					while ((count = is.read(buffer)) != -1) {
						total += count;
						publishProgress(""
								+ (int) ((total * 100) / lenghtOfFile));
						fos.write(buffer, 0, count);
					}

					fos.flush();
					fos.close();
					is.close();

					Intent intentInstall = new Intent(Intent.ACTION_VIEW);
					intentInstall.setDataAndType(Uri.fromFile(new File(
							Environment.getExternalStorageDirectory()
							+ "/elicenter/" + "EliFile.apk")),
					"application/vnd.android.package-archive");
					startActivity(intentInstall);
				} catch (Exception e) {
					e.printStackTrace();
				}
				return null;
			}
		}.execute("");
	}

	public boolean getCheckProduct() {
		try {
			PackageInfo manager = getPackageManager().getPackageInfo(getPackageName(), 0);
			XmlPullParser xmlPullParser = Xml.newPullParser();

			URL url = new URL(URL_LIST_PRODUCT);
			xmlPullParser.setInput(url.openStream(), "UTF-8");

			int eventType;
			@SuppressWarnings("unused")
			String name, size, icon, version, link1, description, pkg;
			int versionCode = 0;
			name = size = icon = version = link1 = description = pkg = "";
			while ((eventType = xmlPullParser.next()) != XmlPullParser.END_DOCUMENT) {
				if (eventType == XmlPullParser.START_TAG) {
					if (xmlPullParser.getName().equals("name")) {
						name = xmlPullParser.nextText();
					} else if (xmlPullParser.getName().equals("package")) {
						pkg = xmlPullParser.nextText();
					} else if (xmlPullParser.getName().equals("size")) {
						size = xmlPullParser.nextText();
					} else if (xmlPullParser.getName().equals("version")) {
						version = xmlPullParser.nextText();
					} else if (xmlPullParser.getName().equals("version-code")) {
						versionCode = Integer.parseInt(xmlPullParser.nextText());
					} else if (xmlPullParser.getName().equals("link")) {
						link1 = xmlPullParser.nextText();
					} else if (xmlPullParser.getName().equals("description")) {
						description = xmlPullParser.nextText();
						if(pkg.equals(manager.packageName)){
							if(versionCode>manager.versionCode){
								oldversion=manager.versionName;
								newversion=version;
								link=link1;
								return false;
							}
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace(System.out);
		}
		return true;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater menuInflater = getMenuInflater();
		menuInflater.inflate(R.menu.menu_local, menu);
		setMenuBackground();
		return super.onCreateOptionsMenu(menu);
	}

	protected void setMenuBackground(){
		Log.d("", "Enterting setMenuBackGround");  
		getLayoutInflater().setFactory( new Factory() {  

			@Override
			public View onCreateView(String name, Context context,
					AttributeSet attrs) {
				if ( name.equalsIgnoreCase( "com.android.internal.view.menu.IconMenuItemView" ) ) {  

					try { 
						LayoutInflater f = getLayoutInflater();  
						final View view = f.createView( name, null, attrs );  
						new Handler().post( new Runnable() {  
							public void run () {  
								view.setBackgroundResource( R.color.menu_option_background);  
							}  
						} );  
						return view;  
					}  
					catch ( InflateException e ) {}  
					catch ( ClassNotFoundException e ) {}  
				}  
				return null;  

			}  
		});  
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_setting:
			Intent intent = new Intent(LocalActivity.this,SettingActivity.class);
			startActivity(intent);
			break;
		case R.id.menu_operator:
			operator();
			break;
		case R.id.menu_new_folder:
			processNewFolder();
			break;
		case R.id.menu_search:
			Intent intentSearch = new Intent(LocalActivity.this,SearchActivity.class);
			startActivity(intentSearch);
			break;
		case R.id.menu_refresh:
			refresh();
			Toast.makeText(this, getString(R.string.reload), Toast.LENGTH_SHORT).show();
			break;
		case R.id.menu_quit:
			runExit();
			break;
		}
		return true;
	}

	public void selectAll() {
		if (local_list.size() > 0) {
			multi = true;
			multiAction = 0;
			multiSelect.clear();
			for (int i = 0; i < local_list.size(); i++) {
				local_list.get(i).setChecked(true);
				multiSelect.add(local_list.get(i));
			}
			refreshMulti();

			((LinearLayout) LocalActivity.this.findViewById(R.id.multiLayout)).setVisibility(LinearLayout.VISIBLE);
			((LinearLayout) LocalActivity.this.findViewById(R.id.normalLayout)).setVisibility(LinearLayout.GONE);
			LinearLayout layout = (LinearLayout) LocalActivity.this.findViewById(R.id.expandLayout);
			layout.setVisibility(LinearLayout.VISIBLE);

		}
	}

	public void refreshMulti() {
		switch (LoadSetting.setting.getDisplay()) {
		case 0:
			// gridview
			initalGridView();
			break;
		case 1:
			// list_view;
			initalListView();
			break;
		case 2:
			// detail_view;
			initalDetailView();
			break;
		default:
			break;
		}
		addressButton.setText(Tool.getLocalPath(Tool.local_path));
	}

	private void runExit(){
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(getString(R.string.exitapp));
		builder.setMessage(getString(R.string.questionexitapp));
		builder.setPositiveButton(getString(R.string.ok),new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				LocalActivity.this.moveTaskToBack(true);
				android.os.Process.killProcess(android.os.Process.myPid());
				android.os.Process.sendSignal(android.os.Process.myPid(), android.os.Process.SIGNAL_KILL);
			}
		});
		builder.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface arg0, int arg1) {
			}
		});
		AlertDialog alertDialog = builder.create();
		alertDialog.show();
	}

	public void processNewFolder(){
		LayoutInflater inflater = (LayoutInflater)getApplicationContext().getSystemService(LAYOUT_INFLATER_SERVICE);
		View view = inflater.inflate(R.layout.newfolder,null);

		final TextView lbFolder = (TextView)view.findViewById(R.id.lbNameFolder);
		final EditText valueFolder = (EditText)view.findViewById(R.id.nameFolder);

		lbFolder.setText(getString(R.string.namefolder));
		lbFolder.setTextColor(Color.WHITE);

		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Add a new folder name");
		builder.setView(view);
		builder.setCancelable(false);

		builder.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				String folder = valueFolder.getText().toString();
				if (folder == null || folder.equals("")) {
					AlertDialog.Builder builder = new AlertDialog.Builder(
							LocalActivity.this);
					builder.setTitle(R.string.warning);
					builder.setMessage(" Input value, please!");
					builder.setPositiveButton(getString(R.string.ok), null);
					builder.show();
					return;
				}
				String path = "";
				if (Tool.local_path.size() > 0) {
					for (int i = 0; i < Tool.local_path.size(); i++) {
						path += File.separator + Tool.local_path.get(i);
					}
				}
				path += File.separator + folder;
				File file = new File(path);
				if (file.exists()) {
					AlertDialog.Builder builder = new AlertDialog.Builder(
							LocalActivity.this);
					builder.setTitle(R.string.duplicate);
					builder.setMessage(R.string.folderexist);
					builder.setPositiveButton(getString(R.string.ok), null);
					builder.show();
					return;
				}
				file.mkdir();
				refresh();
			}
		});

		builder.setNegativeButton(getString(R.string.cancel),new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
			}
		});

		AlertDialog alertDialog = builder.create();
		alertDialog.show();
	}

	// detail
	private void details(LocalFilePojo item) {
		try {
			int lbwidth=screenwidth/3+10;
			int tvwidth=screenwidth-screenwidth/3;
			
			LayoutInflater inflater = (LayoutInflater)getApplicationContext().getSystemService(LAYOUT_INFLATER_SERVICE);
			View viewDelete = inflater.inflate(R.layout.detail_item_ftp, null);
			
			final TextView fname = (TextView)viewDelete.findViewById(R.id.idfilename);
			final TextView ftype = (TextView)viewDelete.findViewById(R.id.idtypefile);
			final TextView fsize = (TextView)viewDelete.findViewById(R.id.idsize);
			final TextView fmodify = (TextView)viewDelete.findViewById(R.id.idmodifydate);
			final TextView flocation = (TextView)viewDelete.findViewById(R.id.idlocationname);

			fname.setText(getString(R.string.file_name)+":");
			ftype.setText(getString(R.string.filetype)+":");
			fsize.setText(getString(R.string.filesize)+":");
			fmodify.setText(getString(R.string.lastmodified)+":");
			flocation.setText(getString(R.string.location)+":");

			final TextView vfname = (TextView)viewDelete.findViewById(R.id.valuenamefile);
			final TextView vftype = (TextView)viewDelete.findViewById(R.id.valuetypefile);
			final TextView vfSize = (TextView)viewDelete.findViewById(R.id.valuesize);
			final TextView vfModify = (TextView)viewDelete.findViewById(R.id.valuemodifydate);
			final TextView vlocation= (TextView)viewDelete.findViewById(R.id.valuenamelocation);
			
			vfname.setText(item.getFileItem().getName());
			vlocation.setText(Tool.getLocalPath(Tool.local_path));
			
			if(item.getFileItem().isDirectory()){
				vftype.setText(getString(R.string.folder));
			}else if(item.getFileItem().isFile()){
				vftype.setText(getString(R.string.file));
			}

			long size = item.getTotalsize();
			if(size<1024){
				vfSize.setText(size +" Bytes");
			}else{
				vfSize.setText((size/1024) + " KB");
			}
			
			vfModify.setText(Tool.format1.format(item.getFileItem().lastModified()));
			
			fname.setWidth(lbwidth);
			vfname.setWidth(tvwidth);
			
			flocation.setWidth(lbwidth);
			vlocation.setWidth(tvwidth);
			
			ftype.setWidth(lbwidth);
			vftype.setWidth(tvwidth);
			
			fsize.setWidth(lbwidth);
			vfSize.setWidth(tvwidth);
			
			fmodify.setWidth(lbwidth);
			vfModify.setWidth(tvwidth);

			AlertDialog.Builder builderDetail = new AlertDialog.Builder(this);
			builderDetail.setTitle(item.getFileItem().getName().toString()+" "+"properties");
			builderDetail.setView(viewDelete);

			builderDetail.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {

				}
			});
			AlertDialog al = builderDetail.create();
			al.show();
		
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onBackPressed() {
		back();
	}

	// delete file
	private void remove(final LocalFilePojo item) {
		try {
			AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(LocalActivity.this);
			dialogBuilder.setTitle(getString(R.string.delete));
			dialogBuilder.setMessage(getString(R.string.areyousure));
			dialogBuilder.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {

					if (multi) {
						if(multiSelect!=null && multiSelect.size()>0){
							for (int i = 0; i < multiSelect.size(); i++) {
								deleteRecursive(multiSelect.get(i).getFileItem());
							}
							multi=false;
							refresh();
							cut = copy = null;
							multiSelect.clear();
							((LinearLayout) LocalActivity.this.findViewById(R.id.multiLayout))
							.setVisibility(LinearLayout.GONE);
							((LinearLayout) LocalActivity.this.findViewById(R.id.normalLayout))
							.setVisibility(LinearLayout.VISIBLE);
							Toast.makeText(LocalActivity.this, R.string.multioff, Toast.LENGTH_SHORT)
							.show();
						}
					}else{
						deleteRecursive(item.getFileItem());
						refresh();
						cut = copy = null;
					}
				}
			});
			dialogBuilder.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {

				}
			});

			AlertDialog al = dialogBuilder.create();
			al.show();
		} catch (Exception e) {
			e.printStackTrace(System.out);
		}
	}

	public void deleteRecursive(File dir)
	{
		if(dir.exists()){
			if (dir.isDirectory())
			{
				String[] children = dir.list();
				for (int i = 0; i < children.length; i++) 
				{
					File temp =  new File(dir, children[i]);
					if(temp.isDirectory())
					{
						deleteRecursive(temp);
					}
					else
					{
						boolean b = temp.delete();
						if(b == false)
						{
							Log.d("DeleteRecursive", "DELETE FAIL");
						}
					}
				}

				dir.delete();
			}
			else if(dir.isFile()){
				dir.delete();
			}
		}
	}

	//	// process remove sub folders and files
	//	private boolean processRemove(File file) {
	//		try {
	//			if (file.isDirectory()) {
	//				String[] child = file.list();
	//				for (int i = 0; i < child.length; i++) {
	//					boolean success = processRemove(new File(file, child[i]));
	//					if (!success) {
	//						return false;
	//					}
	//				}
	//			}
	//		} catch (Exception e) {
	//			e.printStackTrace();
	//		}
	//		return file.delete();
	//	}

	// rename file
	private void rename(String name) {
		try {
			if (!multi) { // dang chon thi khong rename duoc
				if (copy != null || cut != null) { // copy a file or cut a file
					return;
				} else {
					AlertDialog.Builder builder = new AlertDialog.Builder(
							LocalActivity.this);
					final EditText input = new EditText(LocalActivity.this);

					File fileTemp = new File(name);
					String nameFile = fileTemp.getName();

					String type = "";
					if (fileTemp.isFile()) {
						int index = nameFile.lastIndexOf(".");
						if (index > 0 && index <= nameFile.length() - 2) {
							String temp = nameFile;
							nameFile = temp.substring(0, index);
							type = temp.substring(index, temp.length());
						}
					}
					input.setText(nameFile);
					LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
							LinearLayout.LayoutParams.FILL_PARENT,
							LinearLayout.LayoutParams.WRAP_CONTENT);
					input.setLayoutParams(lp);
					input.setLines(1);
					input.setSingleLine(true);
					builder.setView(input);
					builder.setTitle(getString(R.string.file_name));
					final String tempName = nameFile;
					final String tempType = type;
					builder.setPositiveButton(getString(R.string.ok),
							new DialogInterface.OnClickListener() {

						public void onClick(DialogInterface dialog,
								int which) {
							AlertDialog.Builder builder = new AlertDialog.Builder(
									LocalActivity.this);
							String newname = input.getText().toString();
							if (newname == null || newname.equals("")) {
								builder.setTitle(R.string.missinginfo);
								builder.setMessage(R.string.nameempty);
								builder.setPositiveButton(R.string.ok, null);
								builder.show();
								return;
							}
							String path = Tool.getLocalPath(Tool.local_path);
							String despath;
							despath = path;
							path += File.separator+ tempName + tempType;
							despath += File.separator+ newname + tempType;
							File file = new File(path);
							File des = new File(despath);
							if (des.exists()) {
								builder.setTitle(R.string.missinginfo);
								builder.setMessage(R.string.nameexist);
								builder.setPositiveButton(R.string.ok, null);
								builder.show();
								return;
							}
							file.renameTo(des);
							refresh();
						}
					});
					builder.setNegativeButton(getString(R.string.cancel), null);
					builder.show();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void setValuePasteOperator() {
		operator = new String[] {getString(R.string.select_all), getString(R.string.paste) };
	}

	public void pasteCopyOne(){
		if(copy!=null){
			String tempPath=Tool.getLocalPath(Tool.local_path);
			if(tempPath.equals(srcpath) ){
				AlertDialog.Builder builder = new AlertDialog.Builder(this);
				builder.setTitle(getString(R.string.warning));
				builder.setMessage(getString(R.string.copycontaint));
				builder.setCancelable(false);
				builder.setPositiveButton(getString(R.string.cancel),new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {

					}
				});

				builder.show();
			}else{
				final File destPath = new File(tempPath);
				File[] fs = destPath.listFiles();
				if(fs!=null && fs.length>0){
					String srcsub=srcpath;					
					boolean kttrung=false;
					srcsub=srcpath+File.separator+copy.getName();
					if( tempPath.contains(srcsub)){
						AlertDialog.Builder builder = new AlertDialog.Builder(this);
						builder.setTitle(getString(R.string.warning));
						builder.setMessage(copy.getName()+": "+getString(R.string.copycontaint1));
						builder.setCancelable(false);
						builder.setPositiveButton(getString(R.string.cancel),new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog, int which) {

							}
						});

						builder.show();
					}else{

						String dessub = tempPath+File.separator+copy.getName();
						if(srcpath.contains(dessub)){
							AlertDialog.Builder builder = new AlertDialog.Builder(this);
							builder.setTitle(getString(R.string.warning));
							builder.setMessage(copy.getName()+": "+getString(R.string.copycontaint2));
							builder.setCancelable(false);
							builder.setPositiveButton(getString(R.string.cancel),new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog, int which) {

								}
							});

							builder.show();
						}else{
							for(int j=0;j<fs.length;j++){
								if(fs[j].getName().equals(copy.getName())){
									kttrung=true;
								}
							}			

							if(kttrung==true){
								hamtrungcopy(copy,destPath);
							}else{
								if(copy.isDirectory()){
									copyDir(copy, destPath);
								}else{
									processCopyLocalPaste(copy,destPath);
								}
							}
						}
						
					}
				}else{
					if(copy.isDirectory()){
						copyDir(copy, destPath);
					}else{
						processCopyLocalPaste(copy, destPath );
					}
				}
			}
			refresh();
//			cut=copy=null;
		}else{
			Toast.makeText(LocalActivity.this, R.string.chooseafilecopy, Toast.LENGTH_SHORT).show();
		}
	}

	public void operator() {
		AlertDialog.Builder builder = new AlertDialog.Builder(LocalActivity.this);
		builder.setTitle(R.string.operator);
		builder.setItems(operator, new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
				switch (which) {
				case 0:
					selectAll();
					break;
				case 1:
					switch (multiAction) {
					case 1:
						System.out.println("copy mutliaction: "+multiAction);
						pasteCopyMulti();
						break;
					case 2:
						pasteCutMulti();
						break;
					}
					switch (flagCopyCut) {
					case 1:
						if(multiSelect!=null && multiSelect.size()>0){
							System.out.println("copy one mutliaction: "+multiAction);
							pasteCopyMulti();
						}else{
							System.out.println("copy one: "+multiAction);
							pasteCopyOne();// paste file copy
						}
						break;
					case 2:
						if(multiSelect!=null && multiSelect.size()>0){
							System.out.println("cut one mutliaction: "+multiAction);
							pasteCutMulti();
						}else{
							System.out.println("cut one: "+multiAction);
							pasteCutOne();// paste file cut
						}
						break;
					}
					break;
				default:
					break;
				}
			}
		});
		builder.setPositiveButton("Cancel", null);
		builder.show();
	}

	long tongmulti=0;
	long tongb=0;
//	boolean kq=true;
	int vitri=0;
	int tongvitri=0;
	public void pasteCutMulti(){
		if(multiSelect!=null && multiSelect.size() > 0){
//			boolean flagvitri=false;
			tongb=0;
			vitri=0;
			
			tongvitri=multiSelect.size();
//			kq=true;
			String tempPath=Tool.getLocalPath(Tool.local_path);
			System.out.println("src: "+srcpath+" ---- temp: "+tempPath);
			if(tempPath.equals(srcpath) ){
				AlertDialog.Builder builder = new AlertDialog.Builder(this);
				builder.setTitle(getString(R.string.warning));
				builder.setMessage(getString(R.string.copycontaint));
				builder.setCancelable(false);
				builder.setPositiveButton(getString(R.string.cancel),new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {

					}
				});

				builder.show();
			}else{
				final File destPath = new File(tempPath);
				File[] fs = destPath.listFiles();
				if(fs!=null && fs.length>0){
					String srcsub=srcpath;					

					for(int i=0;i<multiSelect.size();i++){
//						if(i==(multiSelect.size()-1)){
//							flagvitri=true;
//						}
						boolean kttrung=false;
						srcsub=srcpath+File.separator+multiSelect.get(i).getFileItem().getName();
						System.out.println("subsrc: "+srcsub+" ---- temp: "+tempPath);
						if( tempPath.contains(srcsub)){
							hamconcut(multiSelect.get(i),1);
						}else{
							String dessub = tempPath+File.separator+multiSelect.get(i).getFileItem().getName();
							if(srcpath.contains(dessub)){
								hamconcut(multiSelect.get(i),2);
							}else{
								for(int j=0;j<fs.length;j++){
									if(fs[j].getName().equals(multiSelect.get(i).getFileItem().getName())){
										kttrung=true;
									}
								}			

								if(kttrung==true){
									hamtrungcut(multiSelect.get(i), destPath);
								}else{
									System.out.println("sourc "+multiSelect.get(i).getFileItem().getName());
									vitri++;
									if(multiSelect.get(i).getFileItem().isDirectory()){
										cutDir(multiSelect.get(i).getFileItem(), destPath);
									}else{
										processCutLocalPaste( multiSelect.get(i).getFileItem(),destPath);
									}
								}
							}
						}

					}
					
				}else{
					System.out.println("copy het");
					for(int i=0;i<multiSelect.size();i++){
						vitri=i+1;
						if(multiSelect.get(i).getFileItem().isDirectory()){
							cutDir(multiSelect.get(i).getFileItem(), destPath);
						}else{
							processCutLocalPaste( multiSelect.get(i).getFileItem(), destPath );
						}
					}
				}

			}

			
			if(multiSelect!=null && multiSelect.size()>0){
				if(tongb==tongmulti){
					if(vitri==tongvitri){
						multi=false;
						for (int i = 0; i < multiSelect.size(); i++) {
							deleteRecursive(multiSelect.get(i).getFileItem());
						}
						refresh();
						cut = copy = null;
						multiSelect.clear();
						((LinearLayout) LocalActivity.this.findViewById(R.id.multiLayout))
						.setVisibility(LinearLayout.GONE);
						((LinearLayout) LocalActivity.this.findViewById(R.id.normalLayout))
						.setVisibility(LinearLayout.VISIBLE);
						Toast.makeText(LocalActivity.this, R.string.multioff, Toast.LENGTH_SHORT)
						.show();
					}
				}
				System.out.println("tongb2222: "+tongb+" --- tongmulti2222: "+tongmulti);
			}
		}else{
			Toast.makeText(LocalActivity.this, R.string.chooseafilecut, Toast.LENGTH_SHORT).show();
		}


	}
	
	private void hamconcut(final LocalFilePojo fcopy,int type){
		System.out.println("sub con con: "+fcopy.getFileItem().getName());
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(getString(R.string.warning));
		if(type==1)
			builder.setMessage(fcopy.getFileItem().getName()+": "+getString(R.string.copycontaint1));
		else
			builder.setMessage(fcopy.getFileItem().getName()+": "+getString(R.string.copycontaint2));
		builder.setCancelable(false);
		builder.setPositiveButton(getString(R.string.cancel),new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				vitri++;
				tongmulti -= fcopy.getTotalsize();
				multiSelect.remove(fcopy);
				System.out.println("tongb1 : "+tongb+" -- tongmulti1: "+tongmulti);
				if(tongb == tongmulti){
					System.out.println("vt: "+vitri+" --- "+tongvitri);
					if(vitri==tongvitri){
						multi=false;
						if(multiSelect!=null && multiSelect.size()>0){
							for (int i = 0; i < multiSelect.size(); i++) {
								deleteRecursive(multiSelect.get(i).getFileItem());
							}
						}
						refresh();
						cut = copy = null;
						objectCut = new LocalFilePojo();
						multiSelect.clear();
						((LinearLayout) LocalActivity.this.findViewById(R.id.multiLayout))
						.setVisibility(LinearLayout.GONE);
						((LinearLayout) LocalActivity.this.findViewById(R.id.normalLayout))
						.setVisibility(LinearLayout.VISIBLE);
						Toast.makeText(LocalActivity.this, R.string.multioff, Toast.LENGTH_SHORT)
						.show();
					}
					
				}
			}
		});

		builder.show();
	}
	
	private void hamconcutOne(final LocalFilePojo fcopy, int type){
		System.out.println("sub con con: "+fcopy.getFileItem().getName());
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(getString(R.string.warning));
		if(type==1)
			builder.setMessage(fcopy.getFileItem().getName()+": "+getString(R.string.copycontaint1));
		else
			builder.setMessage(fcopy.getFileItem().getName()+": "+getString(R.string.copycontaint2));
		builder.setCancelable(false);
		builder.setPositiveButton(getString(R.string.cancel),new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				tongmulti -= fcopy.getTotalsize();
				multiSelect.remove(fcopy);
				System.out.println("tongb3333 : "+tongb+" -- tongmulti333: "+tongmulti);
				
				if(tongb == tongmulti){
					multi=false;
					refresh();
					cut = copy = null;
					objectCut = new LocalFilePojo();
					multiSelect.clear();
					((LinearLayout) LocalActivity.this.findViewById(R.id.multiLayout))
					.setVisibility(LinearLayout.GONE);
					((LinearLayout) LocalActivity.this.findViewById(R.id.normalLayout))
					.setVisibility(LinearLayout.VISIBLE);
					Toast.makeText(LocalActivity.this, R.string.multioff, Toast.LENGTH_SHORT)
					.show();
				}
			}
		});

		builder.show();
	}
	
	private void pasteCutOne(){
		if(objectCut!=null && objectCut.getFileItem()!=null ){
			tongb=0;
			String tempPath=Tool.getLocalPath(Tool.local_path);
			if(tempPath.equals(srcpath) ){
				AlertDialog.Builder builder = new AlertDialog.Builder(this);
				builder.setTitle(getString(R.string.warning));
				builder.setMessage(getString(R.string.copycontaint));
				builder.setCancelable(false);
				builder.setPositiveButton(getString(R.string.cancel),new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {

					}
				});

				builder.show();
			}else{
				final File destPath = new File(tempPath);
				File[] fs = destPath.listFiles();
				if(fs!=null && fs.length>0){
					String srcsub=srcpath;					
					boolean kttrung=false;
					srcsub=srcpath+File.separator+objectCut.getFileItem().getName();
					if( tempPath.contains(srcsub)){
						hamconcutOne(objectCut,1);
					}else{
						
						String dessub = tempPath+File.separator+objectCut.getFileItem().getName();
						if(srcpath.contains(dessub)){
							hamconcutOne(objectCut,2);
						}else{
							for(int j=0;j<fs.length;j++){
								if(fs[j].getName().equals(objectCut.getFileItem().getName())){
									kttrung=true;
								}
							}			

							if(kttrung==true){
								hamtrungcutOne(objectCut,destPath);
							}else{
								if(objectCut.getFileItem().isDirectory()){
									cutDirOne(objectCut.getFileItem(), destPath);
								}else{
									processCutLocalPasteOne(objectCut.getFileItem(),destPath);
								}
							}
						}
						
					}
				}else{
					if(objectCut.getFileItem().isDirectory()){
						cutDirOne(objectCut.getFileItem(), destPath);
					}else{
						processCutLocalPasteOne(objectCut.getFileItem(), destPath );
					}
				}
			}
			refresh();
		}else{
			Toast.makeText(LocalActivity.this, R.string.chooseafilecut, Toast.LENGTH_SHORT).show();
		}
	}

	private void hamtrungcut(final LocalFilePojo fcopy, final File fdestPath){
		System.out.println("xu ly trung :"+fcopy.getFileItem().getName());
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(getString(R.string.warning));
		builder.setMessage(fcopy.getFileItem().getName()+": "+getString(R.string.warningsamefolder));
		builder.setCancelable(false);
		builder.setPositiveButton(getString(R.string.ok),new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				vitri++;
				if(fcopy.getFileItem().isDirectory())
					cutDir( fcopy.getFileItem(),fdestPath);
				else
					processCutLocalPaste(fcopy.getFileItem(),fdestPath);
			}
		});
		builder.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				vitri++;
				tongmulti -= fcopy.getTotalsize();
				multiSelect.remove(fcopy);
				System.out.println("kdjfksdjfksd: "+multiSelect.size());
				System.out.println("tongb1 : "+tongb+" -- tongmulti1: "+tongmulti);
				if(tongb == tongmulti){
					System.out.println("trung vt: "+vitri+" --- "+tongvitri);
					if(vitri==tongvitri){
						multi=false;
						if(multiSelect!=null && multiSelect.size()>0){
							for (int i = 0; i < multiSelect.size(); i++) {
								deleteRecursive(multiSelect.get(i).getFileItem());
							}
						}
						refresh();
						cut = copy = null;
						objectCut = new LocalFilePojo();
						multiSelect.clear();
						((LinearLayout) LocalActivity.this.findViewById(R.id.multiLayout))
						.setVisibility(LinearLayout.GONE);
						((LinearLayout) LocalActivity.this.findViewById(R.id.normalLayout))
						.setVisibility(LinearLayout.VISIBLE);
						Toast.makeText(LocalActivity.this, R.string.multioff, Toast.LENGTH_SHORT)
						.show();
					}
				}
				
			}
		});
		builder.show();
	}
	
	private void hamtrungcutOne(final LocalFilePojo fcopy, final File fdestPath){
		System.out.println("xu ly trung :"+fcopy.getFileItem().getName());
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(getString(R.string.warning));
		builder.setMessage(fcopy.getFileItem().getName()+": "+getString(R.string.warningsamefolder));
		builder.setCancelable(false);
		builder.setPositiveButton(getString(R.string.ok),new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				if(fcopy.getFileItem().isDirectory())
					cutDirOne( fcopy.getFileItem(),fdestPath);
				else
					processCutLocalPasteOne(fcopy.getFileItem(),fdestPath);
			}
		});
		builder.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				multi=false;
				refresh();
				cut = copy = null;
				objectCut = new LocalFilePojo();
				multiSelect.clear();
				((LinearLayout) LocalActivity.this.findViewById(R.id.multiLayout))
				.setVisibility(LinearLayout.GONE);
				((LinearLayout) LocalActivity.this.findViewById(R.id.normalLayout))
				.setVisibility(LinearLayout.VISIBLE);
				Toast.makeText(LocalActivity.this, R.string.multioff, Toast.LENGTH_SHORT)
				.show();
				
			}
		});
		builder.show();
	}
	
//		public void pasteCutMulti(){
//			new Thread(){
//				public void run(){
//					processcut();
//					uiHandlerup.post(new Runnable() {
//	
//						@Override
//						public void run() {
//							if(isUpdateRequiredup){
//							}else{
//								if(tongb==tongmulti){
//									System.out.println("delete di");
//								}
//							}
//	
//						}
//					});
//				}
//			}.start();
//		}

	public void pasteCopyMulti(){
		if(multiSelect!=null && multiSelect.size() > 0){
			String tempPath=Tool.getLocalPath(Tool.local_path);
			System.out.println("src: "+srcpath+" ---- temp: "+tempPath);
			if(tempPath.equals(srcpath) ){
				AlertDialog.Builder builder = new AlertDialog.Builder(this);
				builder.setTitle(getString(R.string.warning));
				builder.setMessage(getString(R.string.copycontaint));
				builder.setCancelable(false);
				builder.setPositiveButton(getString(R.string.cancel),new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {

					}
				});

				builder.show();
			}else{
				final File destPath = new File(tempPath);
				File[] fs = destPath.listFiles();
				if(fs!=null && fs.length>0){
					String srcsub=srcpath;	
					for(int i=0;i<multiSelect.size();i++){
						boolean kttrung=false;
						srcsub=srcpath+File.separator+multiSelect.get(i).getFileItem().getName();
						System.out.println("subsrc: "+srcsub+" ---- temp: "+tempPath);
						if( tempPath.contains(srcsub)){
							System.out.println("sub con con: "+multiSelect.get(i).getFileItem().getName());
							AlertDialog.Builder builder = new AlertDialog.Builder(this);
							builder.setTitle(getString(R.string.warning));
							builder.setMessage(multiSelect.get(i).getFileItem().getName()+": "+getString(R.string.copycontaint1));
							builder.setCancelable(false);
							builder.setPositiveButton(getString(R.string.cancel),new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog, int which) {

								}
							});

							builder.show();
						}else{
							String dessub = tempPath+File.separator+multiSelect.get(i).getFileItem().getName();
							if(srcpath.contains(dessub)){
								AlertDialog.Builder builder = new AlertDialog.Builder(this);
								builder.setTitle(getString(R.string.warning));
								builder.setMessage(multiSelect.get(i).getFileItem().getName()+": "+getString(R.string.copycontaint2));
								builder.setCancelable(false);
								builder.setPositiveButton(getString(R.string.cancel),new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog, int which) {

									}
								});

								builder.show();
							}else{
								for(int j=0;j<fs.length;j++){
									if(fs[j].getName().equals(multiSelect.get(i).getFileItem().getName())){
										kttrung=true;
									}
								}			

								if(kttrung==true){
									System.out.println("xu ly trung :"+multiSelect.get(i).getFileItem().getName());
									hamtrungcopy(multiSelect.get(i).getFileItem(),destPath);
								}else{
									System.out.println("sourc "+multiSelect.get(i).getFileItem().getName());
									if(multiSelect.get(i).getFileItem().isDirectory()){
										copyDir(multiSelect.get(i).getFileItem(), destPath);
									}else{
										processCopyLocalPaste( multiSelect.get(i).getFileItem(),destPath);
									}
								}
							}
						}
					}
				}else{
					System.out.println("copy het");
					for(int i=0;i<multiSelect.size();i++){
						if(multiSelect.get(i).getFileItem().isDirectory()){
							copyDir(multiSelect.get(i).getFileItem(), destPath);
						}else{
							processCopyLocalPaste( multiSelect.get(i).getFileItem(), destPath );
						}
					}
				}

			}
			multi=false;
			refresh();
			cut = copy = null;
			multiSelect.clear();
			((LinearLayout) LocalActivity.this.findViewById(R.id.multiLayout))
			.setVisibility(LinearLayout.GONE);
			((LinearLayout) LocalActivity.this.findViewById(R.id.normalLayout))
			.setVisibility(LinearLayout.VISIBLE);
			Toast.makeText(LocalActivity.this, R.string.multioff, Toast.LENGTH_SHORT)
			.show();
		}else{
			Toast.makeText(LocalActivity.this, R.string.chooseafilecopy, Toast.LENGTH_SHORT).show();
		}
	}

	private void hamtrungcopy(final File fcopy,final File fdestPath){
		System.out.println("abc: "+fcopy.getPath());
		AlertDialog.Builder builder = new AlertDialog.Builder(LocalActivity.this);
		builder.setTitle(getString(R.string.warning));
		builder.setMessage(fcopy.getName()+": "+getString(R.string.warningsamefolder));
		builder.setCancelable(false);
		builder.setPositiveButton(getString(R.string.ok),new DialogInterface.OnClickListener() {

			
			public void onClick(DialogInterface dialog, int which) {
				if(fcopy.isDirectory()){
					copyDir( fcopy,fdestPath);
				}else{
					processCopyLocalPaste(fcopy,fdestPath);
				}
			}
		});
		builder.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {

			}
		});
		builder.show();
	}
	
	public void processCutLocalPaste(final File srcPath, final File dstPath){

		AsyncTask<String, String, Void> asyn = new AsyncTask<String, String, Void>() {

			protected void onPreExecute() {
				LocalActivity.this.showDialog(DIALOG_DOWNLOAD_PROGRESS);
			}

			protected void onProgressUpdate(String... progress) {
				mProgressDialog.setProgress(0);
				mProgressDialog.setTitle(progress[1]);
			}

			public void process( File srcPath, File dstPath){
				InputStream in; 
				try {
					if(srcPath!=null){
						if(dstPath.canWrite()){
							in = new FileInputStream(srcPath);
							mProgressDialog.setMessage(getString(R.string.processing) + srcPath.getName() + " ...");
							System.out.println("ten: "+srcPath.getPath()+" -- size: "+srcPath.length()+" -- d:"+dstPath.getPath());
							File vd =new File(dstPath, srcPath.getName().toString());
							System.out.println("out: "+vd.getPath());
							BufferedOutputStream buffer = new BufferedOutputStream(new FileOutputStream(new File(dstPath, srcPath.getName().toString()))); 
							byte byt[] = new byte[1024]; 
							int i; 
							int total = 0;
							int progress = 0;
							for (long l = 0L; (i = in.read(byt)) != -1; l += i ) {
								buffer.write(byt, 0, i);
								total += i;
								progress = (int)(total*100/srcPath.length());
								if(progress==100){
									tongb+=srcPath.length();
								}
								publishProgress(progress + "", srcPath.getName());
								buffer.flush();
							}
							buffer.close();
							in.close();
						}
					}

				} catch (Exception e) {
					e.printStackTrace();
					tongmulti-=srcPath.length();
				} 
			}


			protected Void doInBackground(String... params) {
				try {
					process(srcPath,dstPath);
				}catch (Exception e) {
					e.printStackTrace();
				}
				return null;
			}


			protected void onPostExecute(Void arg) {
				
				if(tongb==tongmulti){
					System.out.println("vt: "+vitri+" --- "+tongvitri);
					if(vitri==tongvitri){
						System.out.println("end: "+tongb+" --" +tongmulti);
						if(mProgressDialog.isShowing()){
							
							mProgressDialog.dismiss();
						}
						multi=false;
						for (int i = 0; i < multiSelect.size(); i++) {
							deleteRecursive(multiSelect.get(i).getFileItem());
						}
						refresh();
						copy = null;
						objectCut= new LocalFilePojo();
						multiSelect.clear();
						((LinearLayout) LocalActivity.this.findViewById(R.id.multiLayout))
						.setVisibility(LinearLayout.GONE);
						((LinearLayout) LocalActivity.this.findViewById(R.id.normalLayout))
						.setVisibility(LinearLayout.VISIBLE);
						Toast.makeText(LocalActivity.this, R.string.multioff, Toast.LENGTH_SHORT)
						.show();
					}else{
						if(mProgressDialog.isShowing()){
							refresh();
							mProgressDialog.dismiss();
						}
					}
					
				}else if(tongb<tongmulti){
					System.out.println("tongb sub: "+tongb+" --" +tongmulti);
					if(mProgressDialog.isShowing()){
						refresh();
						mProgressDialog.dismiss();
					}
				}else if(tongb>=tongmulti){
					System.out.println("qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq");
				}
				
				
			}
		};
		asyn.execute("");

	}
	
	public void processCutLocalPasteOne(final File srcPath, final File dstPath){

		AsyncTask<String, String, Void> asyn = new AsyncTask<String, String, Void>() {

			protected void onPreExecute() {
				LocalActivity.this.showDialog(DIALOG_DOWNLOAD_PROGRESS);
			}

			protected void onProgressUpdate(String... progress) {
				mProgressDialog.setProgress(0);
				mProgressDialog.setTitle(progress[1]);
			}

			public void process( File srcPath, File dstPath){
				InputStream in; 
				try {
					if(srcPath!=null){
						if(dstPath.canWrite()){
							in = new FileInputStream(srcPath);
							mProgressDialog.setMessage(getString(R.string.processing) + srcPath.getName() + " ...");
							System.out.println("ten: "+srcPath.getPath()+" -- size: "+srcPath.length()+" -- d:"+dstPath.getPath());
							File vd =new File(dstPath, srcPath.getName().toString());
							System.out.println("out: "+vd.getPath());
							BufferedOutputStream buffer = new BufferedOutputStream(new FileOutputStream(new File(dstPath, srcPath.getName().toString()))); 
							byte byt[] = new byte[1024]; 
							int i; 
							int total = 0;
							int progress = 0;
							for (long l = 0L; (i = in.read(byt)) != -1; l += i ) {
								buffer.write(byt, 0, i);
								total += i;
								progress = (int)(total*100/srcPath.length());
								if(progress==100){
									tongb+=srcPath.length();
								}
								publishProgress(progress + "", srcPath.getName());
								buffer.flush();
							}
							buffer.close();
							in.close();
						}
					}

				} catch (Exception e) {
					e.printStackTrace();
					tongmulti-=srcPath.length();
				} 
			}


			protected Void doInBackground(String... params) {
				try {
					process(srcPath,dstPath);
				}catch (Exception e) {
					e.printStackTrace();
				}
				return null;
			}


			protected void onPostExecute(Void arg) {
				
				if(tongb==tongmulti){
					System.out.println("end: "+tongb+" --" +tongmulti);
					if(mProgressDialog.isShowing()){
						multi=false;
						deleteRecursive(objectCut.getFileItem());
						refresh();
						copy = null;
						objectCut= new LocalFilePojo();
						multiSelect.clear();
						((LinearLayout) LocalActivity.this.findViewById(R.id.multiLayout))
						.setVisibility(LinearLayout.GONE);
						((LinearLayout) LocalActivity.this.findViewById(R.id.normalLayout))
						.setVisibility(LinearLayout.VISIBLE);
						Toast.makeText(LocalActivity.this, R.string.multioff, Toast.LENGTH_SHORT)
						.show();
						mProgressDialog.dismiss();
					}
					
				}else if(tongb<tongmulti){
					System.out.println("tongb sub: "+tongb+" --" +tongmulti);
					if(mProgressDialog.isShowing()){
						refresh();
						mProgressDialog.dismiss();
					}
				}else if(tongb>=tongmulti){
					System.out.println("qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq");
				}
				
				
			}
		};
		asyn.execute("");

	}

	public void processCopyLocalPaste(final File srcPath, final File dstPath){
		asyn = new AsyncTask<String, String, Void>() {

			protected void onPreExecute() {
				LocalActivity.this.showDialog(DIALOG_DOWNLOAD_PROGRESS);
			}

			protected void onProgressUpdate(String... progress) {
				mProgressDialog.setProgress(0);
				mProgressDialog.setTitle(progress[1]);
			}

			public void process( File srcPath, File dstPath){
				InputStream in; 
				try {
					if(srcPath!=null){
						if(dstPath.canWrite()){
							mProgressDialog.setMessage(R.string.processing + srcPath.getName() + " ...");
							System.out.println("ten: "+srcPath.getPath()+" -- size: "+srcPath.length()+" -- d:"+dstPath.getPath());
							in = new FileInputStream(srcPath);
							File vd =new File(dstPath, srcPath.getName().toString());
							System.out.println("out: "+vd.getPath());
							BufferedOutputStream buffer = new BufferedOutputStream(new FileOutputStream(new File(dstPath, srcPath.getName().toString()))); 
							byte byt[] = new byte[1024]; 
							int i; 
							int total = 0;
							int progress = 0;
							for (long l = 0L; (i = in.read(byt)) != -1; l += i ) {
								buffer.write(byt, 0, i);
								total += i;
								progress = (int)(total*100/srcPath.length());
								publishProgress(progress + " ", srcPath.getName());
								buffer.flush();
							}

							buffer.close();
							in.close();
						}else{
							System.out.println("not write");
						}
					}else{
						System.out.println("null");
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}


			protected Void doInBackground(String... params) {
				try {
					process(srcPath,dstPath);
				}catch (Exception e) {
					e.printStackTrace();
				}
				return null;
			}


			protected void onPostExecute(Void arg) {
				if (mProgressDialog.isShowing()) {
					mProgressDialog.cancel();
				}
				refresh();
			}
		};
		asyn.execute("");

	}

	public OnClickListener processUploadButton(){
		OnClickListener onclick = new OnClickListener() {

			@Override
			public void onClick(View v) {

			}
		};
		return onclick;
	}

	public void copyDir(File srcPath , File dstPath){
		if(srcPath!=null){
			File dstPath1 = new File(dstPath.getPath()+File.separator + srcPath.getName().toString());
			System.out.println("n: "+srcPath.getPath()+" ---- d: "+dstPath1.getPath());
			if(!dstPath1.exists()){
				dstPath1.mkdirs();	
				File[] files = srcPath.listFiles();

				for( File file : files ) {
					if( file.isDirectory() ) {
						copyDir( file,dstPath1);
					} else {
						processCopyLocalPaste( file, dstPath1);
					}
				}
			}else{
				File[] files = srcPath.listFiles();

				if(files.length>0){
					deleteRecursive(dstPath1);
					dstPath1.mkdirs();
					for( File file : files ) {
						if( file.isDirectory() ) {
							copyDir( file,dstPath1);
						} else {
							processCopyLocalPaste( file, dstPath1 );
						}
					}
				}else{
					deleteRecursive(dstPath1);
					dstPath1.mkdirs();
				}
				
			}
			refresh();
		}else{
			System.out.println("thu muc null");
		}
		
		
	}

	public void cutDir(File srcPath , File dstPath){
		if(srcPath!=null){
			File dstPath1 = new File(dstPath.getPath()+File.separator + srcPath.getName());
			System.out.println("n: "+srcPath.getPath()+" ---- d: "+dstPath1.getPath());
			if(!dstPath1.exists()){
				dstPath1.mkdirs();	
				File[] files = srcPath.listFiles();

				if(files!=null && files.length>0){
					for( File file : files ) {
						if( file.isDirectory() ) {
							cutDir( file,dstPath1);
						} else {
							processCutLocalPaste( file, dstPath1);
						}
					}
				}
				
			}else{
				File[] files = srcPath.listFiles();

				if(files!=null && files.length>0){
					deleteRecursive(dstPath1);
					dstPath1.mkdirs();
					for( File file : files ) {
						if( file.isDirectory() ) {
							cutDir( file,dstPath1);
						} else {
							processCutLocalPaste( file, dstPath1);
						}
					}
				}else{
					deleteRecursive(dstPath1);
					dstPath1.mkdirs();
				}

			}
			
			if(tongb == tongmulti){
				System.out.println("trung thu mucvt: "+vitri+" --- "+tongvitri);
				if(vitri==tongvitri){
					System.out.println("trung cutdir");
					multi=false;
					for (int i = 0; i < multiSelect.size(); i++) {
						deleteRecursive(multiSelect.get(i).getFileItem());
					}
					refresh();
					cut = copy = null;
					objectCut = new LocalFilePojo();
					multiSelect.clear();
					((LinearLayout) LocalActivity.this.findViewById(R.id.multiLayout))
					.setVisibility(LinearLayout.GONE);
					((LinearLayout) LocalActivity.this.findViewById(R.id.normalLayout))
					.setVisibility(LinearLayout.VISIBLE);
					Toast.makeText(LocalActivity.this, R.string.multioff, Toast.LENGTH_SHORT)
					.show();
				}
			}
			
		}else{
			System.out.println("cut null");
		}
		

	}
	
	public void cutDirOne(final File srcPath , File dstPath){
		if(srcPath!=null){
			File dstPath1 = new File(dstPath.getPath()+File.separator + srcPath.getName());
			System.out.println("n: "+srcPath.getPath()+" ---- d: "+dstPath1.getPath());
			if(!dstPath1.exists()){
				dstPath1.mkdirs();	
				File[] files = srcPath.listFiles();

				if(files!=null && files.length>0){
					for( File file : files ) {
						if( file.isDirectory() ) {
							cutDirOne( file,dstPath1);
						} else {
							processCutLocalPasteOne( file, dstPath1);
						}
					}
				}
				
			}else{
				File[] files = srcPath.listFiles();

				if(files!=null && files.length>0){
					deleteRecursive(dstPath1);
					dstPath1.mkdirs();
					for( File file : files ) {
						if( file.isDirectory() ) {
							cutDirOne( file,dstPath1);
						} else {
							processCutLocalPasteOne( file, dstPath1 );
						}
					}
				}else{
					System.out.println("trung thu muc rong");
					deleteRecursive(dstPath1);
					dstPath1.mkdirs();
				}

			}
			
			if(tongb == tongmulti){
				System.out.println("trung cutdir");
				multi=false;
				deleteRecursive(objectCut.getFileItem());
				refresh();
				cut = copy = null;
				objectCut = new LocalFilePojo();
				((LinearLayout) LocalActivity.this.findViewById(R.id.multiLayout))
				.setVisibility(LinearLayout.GONE);
				((LinearLayout) LocalActivity.this.findViewById(R.id.normalLayout))
				.setVisibility(LinearLayout.VISIBLE);
				Toast.makeText(LocalActivity.this, R.string.multioff, Toast.LENGTH_SHORT)
				.show();
			}
			
		}else{
			System.out.println("cut null");
		}
		

	}

	// check exit file
	private int checkExistFile(LocalFilePojo file, ArrayList<LocalFilePojo> arr) {
		if (file != null && arr.size() > 0) {
			for (LocalFilePojo f : arr) {
				if (file.getFileItem().getPath().equals(f.getFileItem().getPath())) {
					return arr.indexOf(f);
				}
			}
		}
		return -1;
	}

	// FAVORITE
	private boolean saveFavorite(LocalFilePojo item) {
		try {
			favoriteConnectSQLite.createNewFavorite(item);
			Toast.makeText(LocalActivity.this, "Saved", Toast.LENGTH_SHORT).show();
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		} 
		return true;
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		favoriteConnectSQLite.close();
	}
}
